package com.qidian.buy.product.controller;

import com.qidian.buy.util.pojo.BuyResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;

/**
 * Author: 戴着假发的程序员
 * Date: 2023-06-20 10:31
 * company: 起点编程
 * Description:
 **/
@RestController
@CrossOrigin
public class ImageUploadController {
    @Value("${imagePath}")
    private String imagePath;

    @Value("${imageBaseUrl}")
    private String imageBaseUrl;

    // 上传的文件的域的名字统一是uploadFile
    @PostMapping("/upload")
    public BuyResult upload(@RequestParam(value = "uploadFile") MultipartFile uploadFile) throws IOException {
        // 处理上传的文件
        // 获取文件的名字
        String fileName = uploadFile.getOriginalFilename();
        // 获取文件名后缀
        String ext = fileName.substring(fileName.lastIndexOf("."));
        // 给文件生成一个随机的物理名
        fileName = UUID.randomUUID().toString().replace("-","") + "_" + (new Random().nextInt(90) + 10) + ext;
        // 将图片写入目标文件
        uploadFile.transferTo(new File(imagePath+fileName));
        // 给客户端响应图片的访问地址
        return  BuyResult.ok(imageBaseUrl + fileName);
    };
}
